﻿using System;
using System.Text;

namespace OpenCompiler.Scanning.Scanners
{
	public unsafe class KeywordOrIdentifierScanner : TokenScanner
	{
		private const string KeywordAndIdentifierCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.0123456789";
		private readonly char[] _keywordAndIdentifierCharacters;

		public KeywordOrIdentifierScanner()
		{
			this._keywordAndIdentifierCharacters = Encoding.Default.GetChars(Encoding.Default.GetBytes(KeywordAndIdentifierCharacters));
		}


		public override bool IsToken(char* stringPointer, int remainingCharacters)
		{
			return TokenHelper.IsCharacter(stringPointer[0], this._keywordAndIdentifierCharacters);
		}

		public override object GetToken(ref char* stringPointer, int remainingCharacters)
		{
			var theString = TokenHelper.GetToken(ref stringPointer, ref remainingCharacters, this._keywordAndIdentifierCharacters);
			var isKeyword = IsKeywordValid(theString);
			if( isKeyword )
			{
				return GetKeywordFromToken(theString);
			} else
			{
				return theString;
			}
		}


		public static bool IsKeywordValid(string token)
		{
			// Todo: Due to moving things around - the Keywords class is kinda lost in this project and can't be referenced
			// need to clean up this. We can't have any try/catch handling - too slow!!!!
			try
			{
				var keyword = GetKeywordFromToken(token);
				return (int) keyword != 0;
			} catch
			{
				return false;
			}
		}

		public static Keyword GetKeywordFromToken(string token)
		{
			var keyword = (Keyword)Enum.Parse(typeof(Keyword), token.ToUpperInvariant());
			return keyword;
		}
	}
}
